<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="类目ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入类目ID"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类目编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入类目编码"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入类目名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['item:category:add']">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="categoryList"
      row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="name" label="类目名称" :show-overflow-tooltip="true" width="130"/>
      <el-table-column prop="id" label="ID" width="100"/>
      <el-table-column prop="code" label="编码" width="100"/>
      <el-table-column label="类目图片" align="center" prop="pic" :show-overflow-tooltip="true" width="100">
        <template slot-scope="scope">
          <img :src="scope.row.pic"  width="60" height="60" />
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="80"/>
      <el-table-column label="创建人" align="center" prop="createBy" width="60"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
      <el-table-column label="修改人" align="center" prop="updateBy" width="60"/>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180" />
      <el-table-column label="操作" align="center"  width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
                     v-hasPermi="['item:category:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['item:category:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['item:category:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="类目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入类目名称" />
        </el-form-item>
        <el-form-item label="类目编码" prop="code">
          <el-input v-model="form.code" placeholder="类目编码" />
        </el-form-item>
        <el-form-item label="类目级别" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="1">一级类目</el-radio>
            <el-radio :label="2">二级类目</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.type == 2" label="上级类目" prop="pid">
          <el-select v-model="form.pid" placeholder="请选择" @change="handleOptionCheck">
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类目排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" ></el-input-number>
        </el-form-item>
        <el-form-item label="类目图片" prop="pic">
          <el-upload
            class="image-uploader"
            :on-remove="handleRemove"
            :action="uploadFile"
            :headers="headers"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            :on-success="handleUploadSuccess"
            accept=".jpg,.jpeg,.png">
            <img v-if="form.pic" :src="form.pic" class="category-image">
            <i v-else class="el-icon-plus image-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory, getCategory, delCategory, addCategory, updateCategory } from "@/api/item/category";
import { getToken } from '@/utils/auth'

export default {
  name: "category",
  data() {
    var validateOption = (rule, value, callback) => {
      if (this.form.type === 2 && (value === undefined || value === null)) {
        callback(new Error('请选择上级菜单'));
      } else {
        callback();
      }
    };
    return {
      uploadFile: process.env.VUE_APP_BASE_API + "/file/upload?path=category",
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      // 遮罩层
      loading: true,
      // 类目表格树数据
      categoryList: [],
      // 菜单树选项
      menuOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "编码不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "请选择类目级别", trigger: "change" }
        ],
        sort: [
          { required: true, message: "类目排序不能为空", trigger: "blur" }
        ],
        pid: [
          { validator: validateOption, trigger: 'change' }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then(response => {
          this.categoryList = response.data.rows;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: undefined,
        code: undefined,
        type: 1,
        pid: undefined,
        sort: 1,
        pic: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleOptionCheck() {
      this.$forceUpdate();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    beforeImageUpload(file) {
      const isAllowed = file.size / 1024  < 200;
      if (!isAllowed) {
        this.$message.error('上传图片大小不能超过 200KB!');
      }
      return isAllowed;
    },
    handleUploadSuccess(res, file) {
      this.form.pic = res.data.url;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品类目";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getCategory(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品类目";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateCategory(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addCategory(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除类目ID为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCategory(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    }
  }
};
</script>

<style>
  .image-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .image-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .image-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }
  .category-image {
    width: 80px;
    height: 80px;
    display: block;
  }
</style>
